# -*- coding: utf8 -*-

import gtk

class Tree(gtk.TreeView):
    def __init__(self, dir1, dir2, structgen):

        # treestore:
        # 1. nombre del dir/arch
        # 2. checkbox status, activo o no
        # 3. checkbox status, inconsistente o no
        # 4. imagen que indica si es directorio
        self.treestore = gtk.TreeStore(str, gobject.TYPE_BOOLEAN, gobject.TYPE_BOOLEAN, gtk.gdk.Pixbuf)

        # armamos el árbol
        dlg = gtk.Dialog()
        # FIXME: ¿más chico?
        self._directpixbuf = dlg.render_icon(gtk.STOCK_DIRECTORY, gtk.ICON_SIZE_MENU)
        self._makeTree(dir1, dir2, structgen)

        # create the TreeView using treestore
        super(PluginTree,self).__init__(self.treestore)
        
        # button events
        self.connect('button-press-event', self._doubleClick)

        # create a TreeViewColumn for the text and icon
        # FIXME: titulo?
        tvcolumn = gtk.TreeViewColumn("Zaraza")
        cell = gtk.CellRendererPixbuf()
        tvcolumn.pack_start(cell, expand=False)
        tvcolumn.add_attribute(cell, "pixbuf", 3)
        cell = gtk.CellRendererText()
        tvcolumn.pack_start(cell, True)
        tvcolumn.add_attribute(cell, 'text', 0)
        self.append_column(tvcolumn)

        # create a TreeViewColumn for the checkbox
        tvcolumn = gtk.TreeViewColumn('Sincronizar')
        cell = gtk.CellRendererToggle()
        cell.set_property('activatable', True)
        cell.connect('toggled', self.synchroMark)
        tvcolumn.pack_start(cell, False)
        tvcolumn.add_attribute(cell, 'active', 1)
        tvcolumn.add_attribute(cell, 'inconsistent', 2)
        self.append_column(tvcolumn)

        self.show()

    def _makeTree(self, dir1, dir2, structgen):
        for nombre, descend in sorted(structgen):
            iconito = self._directpixbuf if descend else None
            nuevonodo = self.treestore.append(padre, [nombre, 0, 0, iconito])
            if descend:
                self._makeTree(nuevonodo, descend)

    def _doubleClick(self, widg, event):
        '''Si es doble, expando/colapso el nodo.'''
        if event.type == gtk.gdk._2BUTTON_PRESS:
            path = self.get_cursor()[0]
            if self.row_expanded(path):
                self.collapse_row(path)
            else:
                self.expand_row(path, False)

    def _getChildren(self, path):
        '''Finds the children of a path.

        @param path: the path to find the children.
        @return Yields the childrens.
        '''

        father = self.treestore.get_iter(path)
        howmanychilds = self.treestore.iter_n_children(father)
        for i in range(howmanychilds):
            child = self.treestore.iter_nth_child(father, i)
            treerow = self.treestore[child]
            yield treerow

    def synchroMark(self, cell, path):
        '''Handles the plugin activation/deactivation.

        When a child gets activated/deactivated, the father is also refreshed
        to show if it's full/partially/not activated. 

        If the father gets activated/deactivated, all the children follow the
        same fate.
        '''
        # invert the active state and make it consistant
        treerow = self.treestore[path]
        newvalue = not treerow[1]
        treerow[1] = newvalue
        treerow[2] = False

        # path can be "?" if it's a father or "?:?" if it's a child
        if ":" not in path:
            # father: let's change the value of all children
            for childtreerow in self._getChildren(path):
                if childtreerow[0] == "gtkOutput":
                    childtreerow[1] = True
                    if newvalue is False:
                        # we're putting everything in false, except this plugin
                        # so the father is inconsistant
                        treerow[2] = True
                else:
                    childtreerow[1] = newvalue
        else:
            # child: let's change the father status
            vals = []
            pathfather = path.split(":")[0]
            father = self.treestore[pathfather]
            for treerow in self._getChildren(pathfather):
                vals.append(treerow[1])
            if all(vals):
                father[1] = True
                father[2] = False
            elif not any(vals):
                father[1] = False
                father[2] = False
            else:
                father[2] = True


class TreesPane(gtk.VBox):
    def __init__(self):
        gtk.VBox.__init__(self)

        self.widg = gtk.Label("None")
        self.pack_start(self.widg)
        self.show_all() 

    def build(self, *args):
        # FIXME: obviamente  meter DOS arboles con un pane
        tree = Tree(*args)
        self.remove(self.widg)
        self.pack_start(tree)
        self.widg = tree

